# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/9/27 3:00 下午
# @Author  : 白辉东
# @Mail    : masterbai2018@outlook.com
# @File    : exceptions.py
# @Software: PyCharm

from rest_framework.views import exception_handler
from django.db import DatabaseError
from rest_framework.response import Response
from rest_framework import status
import logging

logger = logging.getLogger('django')


def custom_exception_handler(exc, context):
    """
    自定义异常处理
    :param exc: 本次请求的异常信息
    :param context: 本次请求的上下文，是一个json形式的request
    :return:
    """
    response = exception_handler(exc, context)

    # rest_framework不识别的异常，这里来继续处理
    if response is None:
        view = context['view']
        # 数据库异常
        if isinstance(exc, DatabaseError):
            logger.error('[%s] %s' % (view, exc))
            response = Response({'message': '服务器内部异常，请联系管理员处理！'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)
    return response
